import { OAuth2Client, TokenPayload } from 'google-auth-library';
import { publicKeysString } from '../assets/google-publickeys';
import jwt from 'jsonwebtoken';

class GoogleService {
    static client = new OAuth2Client();

    async verifyToken(token: string): Promise<TokenPayload | undefined> {
        const ret = jwt.decode(token, { complete: true });
        if (!ret) {
            return;
        }

        const { header, payload } = ret;
        const kid = header.kid!;
        if (!header.kid) {
            ret;
        }
        return new Promise(async (resolve, reject) => {
            const res = await jwt.verify(token, publicKeysString[kid], { algorithms: ['RS256'] }, (err, decoded) => {
                if (err) {
                    reject(err);
                } else {
                    resolve(decoded as TokenPayload);
                }
            });
        })
        
    }
}

export default new GoogleService();